<?php
/*********************************************************
author			Henson
date			2011-4-1
function		公共函数
函数列表：
	getIP();
	getImgWH($Img,$simgW,$simgH);
	cMkDir($dirName);
	writeFile($fileBody,$writeFile,$mode="w");
	_parsePost( $method = "_POST" , $filter="" );
	uploadImage($srcFile=array(), $destFile=array());
	Display($template_name = null);
	Fetch($template_name);
	sendMail($mailContent = array());
	_setcookie($data, $life = 0);
	str2unicode($str);
	unicode_decode($name);
	SHOWCAPTCHA();
	checkMail($email);
	checkPassword($str);
	mb_chunk_split($str,$length,$end);
	errorShow($msg);
	checkIsLogin();
	Location($url = null);
	findImg($cor_id);
	content_replace($content,$id,$type='est',$flg='all');
	uerLevel($point);
	changeEncode($str,$type='u2g');
	requestToStr();
	delCommentPage();
*********************************************************/


//获取ip地址
function getIP(){
	if(@$_SERVER["HTTP_X_FORWARDED_FOR"]){
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}elseif(@$_SERVER["HTTP_CLIENT_IP"]){
		$ip = $_SERVER["HTTP_CLIENT_IP"]; 
	}elseif(@$_SERVER["REMOTE_ADDR"]){
		$ip = $_SERVER["REMOTE_ADDR"]; 
	}elseif(getenv("HTTP_X_FORWARDED_FOR")){
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}elseif(getenv("HTTP_CLIENT_IP")){
		$ip = getenv("HTTP_CLIENT_IP");
	}elseif(getenv("REMOTE_ADDR")){
		$ip = getenv("REMOTE_ADDR");
	}else{
		$ip = "Unknown";
	}
	return $ip;
}

//等比换算图片宽高
function getImgWH($Img,$simgW,$simgH)
{
	$imgInfo=getimagesize($Img);
	if($imgInfo[0] == $imgInfo[1])
	{
		$imgInfo[1] = $simgH;
		$imgInfo[0] = $simgH;
	}
	if($imgInfo[0]>$imgInfo[1])
	{
		if($imgInfo[0] > $simgW)
		{
			$imgInfo[1] = floor($imgInfo[1]*($simgW/$imgInfo[0]));
			$imgInfo[0] = $simgW;
		}
	}
	else
	{
		if($imgInfo[1] > $simgH)
		{
			$imgInfo[0] = floor($imgInfo[0]*($simgH/$imgInfo[1]));
			$imgInfo[1] = $simgH;
		}
	}
	return $imgInfo;
}

//创建目录
function cMkDir($dirName)
{
	if(!is_dir($dirName))
	{
		@mkdir($dirName,0777);
	}
	return true;
}

//写入文件
function writeFile($fileBody,$writeFile,$mode="w")
{
	//打开文件清空
	$fRs = @fopen($writeFile,$mode);
	$htmlFile = @fwrite($fRs,$fileBody);
	@fclose($fRs);
	return true;
}

//解析post字符串
function _parsePost( $method = "_POST" , $filter="" )
{
	if($method=='_POST')
		$array = $_POST;
	elseif($method=='_GET')
		$array = $_GET;
	elseif($method=='_REQUEST')
		$array = $_REQUEST;

	if(is_array($filter) && !empty($filter) )
	{
		foreach( $filter as $fk=>$fv)
		{
			unset($array[$fv]);
		}
	}elseif ($filter!="")
	{
		unset($array[$filter]);	    
	}
	
	foreach ($array as $pk=>$pv) {
		if(is_array($pv))
			foreach ($pv as $psk=>$psv) 
			{
				$s .=urlencode($pk."[]")."=".urlencode($psv)."&";
			}
		else{	
				$s .=urlencode($pk)."=".urlencode($pv)."&";
		}
	}
	return $s;
}

//上传图片
/****************************
example:
	$srcFile = $_FILES['upload_img'];
	$destFile = array('width'=>'200','height'=>'160','img_name'=>'cor_001','upload_path'=>'/corporation/2011-04-01/');
****************************/
function uploadImage($srcFile=array(), $destFile=array())
{
	if (is_uploaded_file($srcFile['tmp_name']) && $srcFile['error'] == '0')
	{
		$maxwidth = @$destFile['width'];
		$maxheight = @$destFile['height'];
		
		$img_size = getimagesize($srcFile['tmp_name']);
		$width = $img_size[0];
		$height = $img_size[1];
		

		$file_info = pathinfo($srcFile["name"]); 
		$file_ext = $file_info["extension"]; 
		$upload_path = $destFile['upload_path'];
		
		cMkDir($upload_path);
		if (isset($destFile['img_name'])){
			$img_name = $destFile['img_name'];
			$srcFile['name'] = $img_name.'.'.$file_ext; //重命名
		}
		
		$destFile['filename'] = $upload_path.$srcFile['name']; //完整文件名

		if (($maxwidth == "" && $maxheight == "") || ($width <= $maxwidth && $height <= $maxheight))
		{
			move_uploaded_file($srcFile["tmp_name"],$destFile["filename"]);
		}
		else
		{
			$im = @imagecreatefromjpeg($srcFile["tmp_name"]);
			if(!$im){
				$im = @imagecreatefrompng($srcFile["tmp_name"]);
			}
			if(!$im){
				$im = @imagecreatefromgif($srcFile["tmp_name"]);
			}
			if($im){

				if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
					if($maxwidth && $width > $maxwidth){
					$widthratio = $maxwidth/$width;
					$RESIZEWIDTH=true;
					}
					if($maxheight && $height > $maxheight){
					$heightratio = $maxheight/$height;
					$RESIZEHEIGHT=true;
					}
					if($RESIZEWIDTH && $RESIZEHEIGHT){
						if($widthratio < $heightratio){
							$ratio = $widthratio;
						}else{
							$ratio = $heightratio;
						}
					}elseif($RESIZEWIDTH){
						$ratio = $widthratio;
					}elseif($RESIZEHEIGHT){
						$ratio = $heightratio;
					}
					$newwidth = $width * $ratio;
					$newheight = $height * $ratio;
					if(function_exists("imagecopyresampled")){
						$newim = imagecreatetruecolor($newwidth, $newheight);
						imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					}else{
						$newim = imagecreate($newwidth, $newheight);
						imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					}
					imagejpeg($newim,$destFile['filename']);
					imagedestroy ($newim);
				}else{
					imagejpeg($im,$destFile['filename']);
				}

				imagedestroy ($im);
				return true;
			}else{
				return "ERROR:缩略图创建失败,可能您上传的类型不对";
			}
		}
	}
	else
	{
		return "error:图片上传有误";
	}
}

//显示页面
function Display($template_name = null) {
	global $smarty;
	if ( !$template_name  ) {
		$template_name = array_shift(explode('.',basename($_SERVER["SCRIPT_FILENAME"]))) . '.tpl';
	}
	$smarty->assign("template_name", $template_name);
	$smarty->display("layout.tpl");
}
//
//获取页面
function Fetch($template_name = null) {
	global $smarty;
	if ( !$template_name  ) {
		$template_name = array_shift(explode('.',basename($_SERVER["SCRIPT_FILENAME"]))) . '.tpl';
	}
	$smarty->assign("template_name", $template_name);
	return $smarty->fetch("layout.tpl");
}

//发送邮件
function sendMail($mailContent = array())
{
	include 'PHPMailer/class.phpmailer.php';
	try {
		$mail=new PHPMailer();
		$mail->IsSMTP();
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
		$mail->Port       = 465;                   // set the SMTP port 

		$mail->Username   = "itzhixiao@gmail.com";  // GMAIL username
		$mail->Password   = "itzhixiao@320684";            // GMAIL password

		$mail->From       = "itzhixiao@gmail.com";
		$mail->FromName   = "【IT知晓】";
		$mail->Subject    = $mailContent['subject'];
		$mail->Body       = $mailContent['body'];                      //HTML Body
		$mail->AltBody    = $mailContent['body']; //Text Body
		$mail->CharSet	  = "UTF-8";
		$mail->WordWrap   = 50; // set word wrap

		$mail->AddAddress($mailContent['email'],$mailContent['name']);
		$mail->AddReplyTo("itzhixiao@gmail.com","【IT知晓】");
		//$mail->AddAttachment("/path/to/file.zip");             // attachment
		//$mail->AddAttachment("/path/to/image.jpg", "new.jpg"); // attachment

		$mail->IsHTML(true); // send as HTML
		$mail->Send();
		return 'success';
	} catch (phpmailerException $e) {
		return $e->errorMessage();
	}
}

//设置cookie
function _setcookie($data, $life = 0) {
	global $_SERVER;
	if(is_array($data)){
		$domain = '.87dianping.com';
		$sec = ($_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
		$life = ($life ? time() + $life : 0);
		foreach($data as $var=>$value){
			setcookie("d_".$var, $value, $life, '/', $domain, $sec);
		}
	}
}
//
function _getcookie($name){
	if(isset($_COOKIE['d_'.$name])){
		return $_COOKIE['d_'.$name];
	}else{
		return null;
	}
}

function str2unicode($str){   
	$len = mb_strlen($str,"utf-8");
	for($i= 0;$i<$len;$i++){   
		$char = mb_substr($str,$i,1,"utf-8");
		if(!(strlen($char)>1)){   
			$dec = ord($char);   
			if($dec>16){   
				$ret .= "%".$dec;
			}else{   
				$ret .= "%".$dec;
			}
		}
		else
		{   
			$temp = base_convert(bin2hex($char),16,2);   
			$temp = substr($temp,4,4).substr($temp,10,6).substr($temp,18);   
			$ret .= "%".hexdec(strtoupper(base_convert($temp,2,16)));
		}
	}
	return	$ret;   
}
function unicode_decode($name)
{
	// 转换编码，将Unicode编码转换成可以浏览的utf-8编码
	$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
	preg_match_all($pattern, $name, $matches);
	if (!empty($matches))
	{
		$name = '';
		for ($j = 0; $j < count($matches[0]); $j++)
		{
			$str = $matches[0][$j];
			if (strpos($str, '\\u') === 0)
			{
				$code = base_convert(substr($str, 2, 2), 16, 10);
				$code2 = base_convert(substr($str, 4), 16, 10);
				$c = chr($code).chr($code2);
				$c = iconv('UCS-2','UTF-8', $c);
				$name .= $c;
			}
			else
			{
				$name .= $str;
			}
		}
	}
	return $name;
}
//获取验证码
function SHOWCAPTCHA(){
	@ob_end_clean(); //清除之前出现的多余输入
	$captcha = new captcha();
	$captcha->generate_image();
	exit;
}
function checkMail($email) {
	return preg_match("/^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$/", $email);
}
function checkPassword($str)
{
	return preg_match('/^[a-zA-Z0-9]{6,30}$/',$str);
}

function  mb_chunk_split($str,$length,$end)   
{      
    if (empty($str)) return false;   
    return chunk_split($str, $length, $end);   
}   


function errorShow($msg)
{
	echo '<script language="javascript">
	<!--
		alert("'.$msg.'");
		//window.history.go(-1);
	-->
		</script>';
	//die;
}

//判断是否已登录
function checkIsLogin()
{
	$cookie_user_id = intval(_getcookie("id"));
	if($cookie_user_id > 0){
		return true;
	}else{
		return false;
	}
}

//页面跳转
function Location($url = null){
	$location = null;
	if ( !$url) {
		$url = $_SERVER['PHP_SELF'];
	}
	elseif ( substr($url,0,1) == '?' ) {
		$url = $_SERVER['PHP_SELF'] . $url;
	}
	if ( substr($url,0,7) === 'http://' or substr($url,0,8) === 'https://' ) {
		$location = $url;
	}
	else {
		$port = null;
		if ( $_SERVER['SERVER_PORT'] == 443 ) {
			$protocol = 'https://';
		}
		elseif ( $_SERVER['SERVER_PORT']  == 80 ) {
			$protocol = 'http://';
		}
		else {
			$protocol = 'http://';
			$port = ':'. $_SERVER['SERVER_PORT'] ;
		}

		$dir = dirname($_SERVER['SCRIPT_NAME']);
		if ( $dir === "/" ) {
			$dir = "";
		}
		if ( substr($url,0,2) === './' ) {
			if ( $dir ) {
				$location = $protocol . $_SERVER['HTTP_HOST'] . $port . '/' . $dir	. '/' . basename($url);
			}
			else {
				$location = $protocol . $_SERVER['HTTP_HOST'] . $port . '/' . basename($url);
			}
		}
		elseif ( substr($url,0,1) === "/" ) {
			$location = $protocol .$_SERVER['HTTP_HOST'] . $port . $url;
		}
		else {
			$location = $protocol . $_SERVER['HTTP_HOST'] . $port . $dir . '/' . $url;
		}
	}

	header("Location: $location");
	exit();

}
//根据企业ID查找图片
function findImg($id,$type="cor")
{
	$img_arr = array('jpg','png','gif','bmp');
	foreach($img_arr as $imgType)
	{
		if($type == "cor"){
			$imgPath = _IMG_PATH."corporation/".$id."/cor.".$imgType;
			if(file_exists($imgPath)){
				return _HOST_ROOT."/images/corporation/".$id."/cor.".$imgType;
			}
		}elseif($type == "face"){
			$imgPath = _IMG_PATH."userface/".$id."/face.".$imgType;
			if(file_exists($imgPath)){
				return _HOST_ROOT."/images/userface/".$id."/face.".$imgType;
			}
		}
		
	}
	return '';
}

//替换图片等操作
function content_replace($content,$id,$type='est',$flg='all')
{
	$content = str_replace("&lt;br /&gt;","<br/>",$content);
	$content = str_replace("&amp;nbsp;"," ",$content);
	$content = preg_replace("#&lt;img src=&quot;"._HOST_ROOT."/images/face/(\d){1,2}.gif&quot; /&gt;#isU",'*$1',$content);
	if($flg=="all")
	{
		$cont_len = mb_strlen($content, "utf-8");
		if($cont_len > 100){
			$sub_len = 100;
			$sub_str = mb_substr($content,0,$sub_len,"utf-8");
			$left_str = mb_substr($content,$sub_len,mb_strlen($content, "utf-8"),"utf-8");
			if(mb_strlen($left_str, "utf-8") > 50){
				if(substr($sub_str,-1) == '*'){
					for($i=1;$i<=2;$i++){
						if(preg_match('/^(\d){1}$/',mb_substr($content,$sub_len,1,"utf-8")) == 1){
							$sub_len++;
						}else{
							break;
						}
					}
				}
				$sub_str = mb_substr($content,0,$sub_len,"utf-8");
				$content = mb_substr($content,0,$sub_len,"utf-8").'<a class="showAll" href="javascript:;" name="'.$type.'_'.$id.'" title="点击查看全部">......<br/>显示全部</a><span id="'.$type.'_'.$id.'" style="display:none;">'.mb_substr($content,$sub_len,mb_strlen($content, "utf-8"),"utf-8").'</span>';
			}
		}
	}
	$content =  preg_replace("/\*(\d){1,2}/",'<img src="'._HOST_ROOT.'/images/face/$1.gif">',$content);
	return $content;
}

//会员等级
function uerLevel($point)
{
	$point = intval($point);
	$level = "";
	if($point <= 100){
		$level = "试用期";
	}elseif($point <= 500){
		$level = "正式员工";
	}elseif($point <= 1000){
		$level = "助理";
	}elseif($point <= 2500){
		$level = "组长";
	}elseif($point <= 5000){
		$level = "副经理";
	}elseif($point <= 8000){
		$level = "经理";
	}elseif($point <= 12000){
		$level = "高级经理";
	}elseif($point <= 16000){
		$level = "主管";
	}elseif($point <= 20000){
		$level = "副总监";
	}elseif($point <= 25000){
		$level = "总监";
	}elseif($point <= 35000){
		$level = "首席运营官";
	}elseif($point <= 50000){
		$level = "首席执行官";
	}elseif($point <= 80000){
		$level = "副总裁";
	}elseif($point <= 120000){
		$level = "总裁";
	}elseif($point <= 180000){
		$level = "董事";
	}elseif($point <= 250000){
		$level = "执行董事";
	}elseif($point <= 400000){
		$level = "董事长";
	}else{
		$level = "商界领袖";
	}

	return $level;
}
function changeEncode($str,$type='u2g'){
	if($type == 'u2g'){
		return iconv("UTF-8","gb2312//IGNORE",$str);
	}else if($type == 'letv'){
		return iconv("UTF-8","gbk",$str);
	}else{
		return iconv("gb2312","UTF-8",$str);
	}
}
function requestToStr(){
	$arr = array();
	foreach($_POST as $key=>$value){
		if($value != ""){
			if(is_array($value) && count($value) > 0){
				foreach($value as $kk=>$vv){
					$arr[] = $key."[]=".trim($vv);
				}
			}else{
				$arr[] = $key."=".trim($value);
			}
		}
	}
	foreach($_GET as $key=>$value){
		if($value != ""){
			if(is_array($value) && count($value) > 0){
				foreach($value as $kk=>$vv){
					$arr[] = $key."[]=".trim($vv);
				}
			}else{
				$arr[] = $key."=".trim($value);
			}
		}
	}

	return implode("&",$arr);
}

/*删除用户评论后的缓存页面并返回跳转的页面*/
function delCommentPage()
{
	$ref = $_SERVER['HTTP_REFERER'];
	if(preg_match('#/corporation/(\d+)/$#isU', $ref, $matches)){
		$id = $matches[1];
		unlink(_CORPORATION_PATH.$id."/index.html");
		unlink(_CORPORATION_PATH.$id."/comment_1.html");
	}elseif(preg_match('#/corporation/(\d+)/comment_(\d+).html$#isU', $ref, $matches)){
		$id = $matches[1];
		$p = $matches[2];
		unlink(_CORPORATION_PATH.$id."/index.html");
		unlink(_CORPORATION_PATH.$id."/comment_1.html");
	}
	return $ref;
}

?>